#include <vesa/vesa.h>

static int width, height;
static int tw, th;
static int ccol, cline;
static char* fbuf = NULL;
static struct vesaModeInfo minfo;
static int charw = 8, charh = 12;
static int bpp;
static int cur_color = 0xeb02cc;

extern unsigned char char_data[256][12];

int cdrawchar(int line, int col, char ch, int color)
{
	int x = col * charw;
	int y = line * charh;
	int i;
	int j;
	for (i=0; i<charh; i++)
		for (j=0; j<charw; j++)
		{
			if (char_data[ch][i] & (1 << (charw-j)))
			{
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp] = (color & 0xff0000) >> 16;
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp+1] = (color & 0xff00) >> 8;
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp+2] = color & 0xff;
			} else {
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp] = 0;
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp+1] = 0;
				fbuf[(y + i) * minfo.pitch + (x + j) * bpp+2] = 0;
			}
		}

	return 0;
}

int cclear()
{
	memset(fbuf, 0, (minfo.bpp + 1) / 8 * minfo.Xres * minfo.Yres);
	return 0;
}

int cputc(char ch)
{
	cdrawchar(cline, ccol, ch, cur_color);
	ccol++;
	if (ccol == tw)
	{
		cline++;
		ccol = 0;
	}
	if (ch == 10)
	{
		cline++;
//	if (ch == 13)
		ccol = 0;
	}
	if (cline == th)
	{
		cclear();
		cline = 0;
		ccol = 0;
	}
	return 0;
}

int csetcolor(int color)
{
	cur_color = color;
}

int cprintf(char *text)
{
	while (*text)
	{
		cputc(*text);
		text++;
	}
}

static int load_fonts()
{
	char *font;
	int fontsize;
//	rkv_get("font", &font, &fontsize);

}

static int module_load()
{
	struct vesaControllerInfo info;
	vesa_get_controller_info(&info);

	return 0;
	int i;
	int ok = 0;
	for (i=0; i<info.modeCount; i++)
	{
		vesa_get_mode_info_byid(i, &minfo);
		if ((minfo.Xres == 800) && (minfo.Yres == 600) && (minfo.bpp == 24))
		{
			vesa_set_mode(minfo.mode_no);
			ok = 1;
			break;
		}
	}
	if (!ok)
	{
		printf("Failed to get a 800x600x24 console\n");
		return 1;
	}

	tw = minfo.Xres / charw;
	th = minfo.Yres / charh;
	bpp = (minfo.bpp + 1) / 8;

	fbuf = (char*)vmalloc(0x10000000, minfo.physbase);
	cclear();

	load_fonts();

	cprintf("Welcome to VESA console!\n");
	csetcolor(0x123892);
	cprintf("Welcome to VESA console!\n");
	csetcolor(0xdeadbe);
	cprintf("Welcome to VESA console!\n");
	csetcolor(0xfaceb0);
	cprintf("Welcome to VESA console!\n");
	export_symbol("cprintf", &cprintf, 1);
	return 0;
}

static int module_unload(void)
{
	if (fbuf)
	{
		vfree(fbuf);
		fbuf = NULL;
	}
	return 0;
}

